
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using Ixyu.Base.Configs;
using Ixyu.Base.Configs.Dtos;
using Ixyu.Dtos;
using Ixyu.Health;
using Ixyu.Health.Dtos;
using Ixyu.Health.DomainService;
using Ixyu.Helper;


namespace Ixyu.Health
{
    /// <summary>
    /// DailyLife应用层服务的接口实现方法  
    ///</summary>
//    [AbpAuthorize]
    public class DailyLifeAppService : IxyuAppServiceBase
    {
        private readonly IRepository<DailyLife, int> _entityRepository;
        private readonly IRepository<DailyItem, int> _itemRepository;

        private readonly IDailyLifeManager _entityManager;
        private readonly DailyLifeEditDto day;
        private readonly AbpConfigAppService config;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public DailyLifeAppService(
        IRepository<DailyLife, int> entityRepository,
        IRepository<DailyItem, int> itemRepository
        , IDailyLifeManager entityManager,
        AbpConfigAppService service
        )
        {
            _entityRepository = entityRepository;
            _entityManager = entityManager;
            _itemRepository = itemRepository;
            config = service;
            #region DailyLifeEditDto Init


            day = new DailyLifeEditDto();
            day.Title = "";
            day.Note = "";
            day.BloodPressureHeight = 130;
            day.BloodPressureLow = 90;
            day.Weight = 90;
            var items = new List<DailyItemEditDto>();
            items.Add(new DailyItemEditDto
            {
                Name = "戒烟",
                Integral = 0,
                Icon = "md-no-smoking"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "节食",
                Integral = 0,
                Icon = "ios-basket"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "运动",
                Integral = 0,
                Icon = "ios-football"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "环保",
                Integral = 0,
                Icon = "md-bicycle"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "作息",
                Integral = 0,
                Icon = "md-git-compare"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "英语",
                Integral = 0,
                Icon = "md-school"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "陪伴",
                Integral = 0,
                Icon = "ios-home-outline"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "形象",
                Integral = 0,
                Icon = "ios-bowtie"
            });
            items.Add(new DailyItemEditDto
            {
                Name = "血压",
                Integral = 0,
                Icon = "md-pulse"
            });
            day.Items = items;
            day.Pics = new List<FileDto>();

            #endregion
        }


        /// <summary>
        /// 获取DailyLife的分页列表信息
        ///</summary>
        /// <param name="page"></param>
        /// <returns></returns>

        public async Task<PagedResultDto<DailyLifeListDto>> GetPaged(int page=1)
        {

            var query = _entityRepository.GetAll().Where(u => u.CreatorUserId == 1);
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(" Id desc ").AsNoTracking()
                    .PageBy((page-1)*50,50)
                    .ToListAsync();

            var entityListDtos = entityList.MapTo<List<DailyLifeListDto>>();

            return new PagedResultDto<DailyLifeListDto>(count, entityListDtos);
        }
        public async Task<DailyLifeEditDto> GetToday()
        {
            var entity = getToday();
            if (entity != null)
            {
                var items = _itemRepository.GetAllList(u => u.DailyLifeId == entity.Id);
                entity.Items = items.OrderBy(u => u.Id).ToList();
                var dto = entity.MapTo<DailyLifeEditDto>();
                dto.Pics = entity.Photos.Split(',').Select(u => new FileDto() { Name = u.Substring(u.IndexOf('-')), Url = u }).ToList();
                return dto;
            }
            return day;
        }

        public async Task<DailyLifeEditDto> GetByKey(int id)
        {
            var entity = _entityRepository.GetAllIncluding(u=>u.Items).SingleOrDefault(u=>u.Id==id);
                var dto = entity.MapTo<DailyLifeEditDto>();
            dto.Pics = entity.Photos.ToFileList();
                return dto;
           
        }

        private DailyLife getToday()
        {
            return _entityRepository.FirstOrDefault(u => u.CreatorUserId == 1 && u.CreationTime >= DateTime.Now.Date && u.CreationTime < DateTime.Now.AddDays(1).Date);
        }
        public async Task<string>  GetSaying()
        {
            var sayings = await config.GetByKey<List<SayingDto>>("Saying");
            return sayings[(new Random()).Next(sayings.Count)].Title;
        }
        /// <summary>
        /// 添加或者修改DailyLife的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task CreateOrUpdate(CreateOrUpdateDailyLifeInput input)
        {
            var model = getToday();
            if (model != null)
            {
                await Update(input.DailyLife);
            }
            else
            {
                await Create(input.DailyLife);
            }
        }

        /// <summary>
        /// 新增DailyLife
        /// </summary>

        protected virtual async Task Create(DailyLifeEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            var entity = ObjectMapper.Map<DailyLife>(input);
            //var entity=input.MapTo<DailyLife>();
            entity.CreatorUserId = 1;
            entity.Photos = string.Join(",", input.Pics.Select(u => u.Url).ToArray());
            entity.Integral = input.Items.Sum(u => u.Integral);
            await _entityRepository.InsertAsync(entity);
        }

        /// <summary>
        /// 编辑DailyLife
        /// </summary>

        protected virtual async Task Update(DailyLifeEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var model = _entityRepository.GetAll().Include(u => u.Items).SingleOrDefault(u => u.Id == input.Id);
            foreach (var dailyItem in model.Items)
            {
                var item = dailyItem;
                var dto = input.Items.Find(u => u.Id == item.Id);
                dailyItem.Integral = dto.Integral;
            }

            model.Note = input.Note;
            model.Title = input.Title;
            model.CreatorUserId = 1;
            model.Photos = string.Join(",", input.Pics.Select(u => u.Url).ToArray());
            model.Integral = input.Items.Sum(u => u.Integral);
            await _entityRepository.UpdateAsync(model);
        }
    }
}


